/*
* @Date: 2021/2/27
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import React from 'react';
import ajax from 'decorate/ajax';
import postList from 'business/postList';
import Pulldown from 'components/Pulldown';
import Pullup from 'components/Pullup';
import NoData from '../NoData';
import PostItem from '../PostItem';

@ajax(postList.url, postList.meta, postList.resolve)
export default class extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      currentDate: XUE.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
      data: [],
    };
  }

  componentWillReceiveProps (nextProps, nextContext) {
    const { data = [], cur } = nextProps;
    const { page = 1 } = this.state;
    console.log('next data===>', data, page, nextProps);
    if (page === 1) {
      this.setState({
        data,
        page: cur,
      });
    } else {
      let stateData = this.state.data;
      stateData = stateData.concat(data);
      this.setState({
        data: stateData,
      });
    }
  }

  onLoadPost = () => {
    const currentDate = XUE.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
    this.setState({
      page: 1,
      currentDate,
    });
    return this.postAjax({
      data() {
        return {
          page: 1,
          currentDate,
        };
      },
    });
  }

  onLoadMore = () => {
    const { page, currentDate } = this.state;
    return this.postAjax({
      data() {
        return {
          page: page + 1,
          currentDate,
        };
      },
    });
  }

  onVoteEnd = (vo) => {
    const { post, status, vote, postModal } = vo;
    const { data } = this.state;
    const postIndex = data.findIndex(v => v.id === post);
    console.log('vote end===>', post, postIndex, postModal);
    if (postIndex >= 0) {
      const p = data[postIndex];
      if (status === 1) {
        delete p.vote;
      } else {
        p.vote = vote;
      }
      p.hot = postModal.hot;
      p.upvote = postModal.upvote;
      p.downvote = postModal.downvote;
      data[postIndex] = p;
      this.setState({
        data,
      });
    }
  }

  render() {
    const { show = false } = this.props;
    const { data = [] } = this.state;
    if (data.length === 0) {
      return (
        <Pulldown
          onLoading={this.onLoadPost}
          style={{display: show ? 'block' : 'none'}}
        >
          <NoData />
        </Pulldown>
      );
    }
    return (
      <div style={{display: show ? 'block' : 'none'}}>
        <Pulldown
          onLoading={this.onLoadPost}
        >
          <Pullup
            onLoading={this.onLoadMore}
          >
            {
              data.map(vo => (
                <PostItem {...this.props} {...vo}  key={vo.id} onVoteEnd={this.onVoteEnd} />
              ))
            }
          </Pullup>
        </Pulldown>
      </div>
    )
  }
}
